package com.banmao.snake_client.loginScene.controller;

import com.banmao.snake_client.netty.client.ClientService;
import com.banmao.snake_client.netty.handler.LoginResponseHandler;
import com.banmao.snake_core.netty.message.impl.LoginRequestMessage;
import com.banmao.snake_core.netty.message.impl.LoginResponseMessage;
import com.banmao.snake_core.util.ToastUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.concurrent.DefaultPromise;
import javafx.event.ActionEvent;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class LoginController {

    public TextField username_text;

    public PasswordField password_text;


    public void login(ActionEvent actionEvent) throws Exception {
        String username = username_text.getText();
        String password = password_text.getText();

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            ToastUtil.toast("用户名或密码不能为空！");
            return;
        }

        LoginRequestMessage loginRequestMessage = new LoginRequestMessage();
        loginRequestMessage.setUsername(username);
        loginRequestMessage.setPassword(password);

        Channel channel = ClientService.getChannel();

        channel.writeAndFlush(loginRequestMessage);

        LoginResponseHandler.makePromise(loginRequestMessage, channel);

        //ChannelFuture future = channel.writeAndFlush(loginRequestMessage);
        //future.sync();
        //
        //if(future.isSuccess()) {
        //    Void res = future.get();
        //    log.info("登陆请求的响应:{}", res);
        //} else {
        //    Throwable cause = future.cause();
        //    log.error("登陆失败, msg:{}, error:", cause.getCause(), cause);
        //}

    }
}
